# -*- encoding: utf-8 -*-

"""
@File:      service.py
@Time:      2022/08/15 16:18:47
@Author:    zhangtaibo.ztb
@Version:   1.0
@Contact:   zhangtaibo.ztb@alibaba-inc.com
@License:   Mulan PSL v2
"""

import time
from common.sysinfo import SysInfo

class ServiceManager():
    """
    Common def for service manager.
    """

    def __init__(self):
        self.cmd = SysInfo.cmd()

    def service_test(self, service_name, host="local"):
        if not service_name:
            self.log.info("service name is null, please check!")
            return 1
        
        for service in service_name.split():
            # get service's pre status
            ret_c, ori_acti_stat = self.cmd("systemctl is-active %s" % service, host, ignore_status=True)
            service_action = ["restart", "stop", "start", "status"]
            ret_c, rec_o = self.cmd("systemctl status %s | grep -Eo\
            '/usr/lib/systemd/system/.*.service' | xargs grep ExecReload" % service, host, ignore_status=True)
            if ret_c is 0:
                service_action.append("reload")
            for action in service_action:
                self.cmd("systemctl %s %s" % (action, service), host)
                time.sleep(5) # Some services are configured with a start rate limit of 5 seconds
            
            # restore service's status
            if ori_acti_stat == "inactive":
                self.cmd("systemctl stop %s" % service, host)
        return 0  

